﻿using Enity101.Models;
using Entity101.Data.Models;
using Entity101.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity.Migrations;

namespace Enity101.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index() {
            IndexViewModel vm = new IndexViewModel();
            vm.PageName = "Showing the posts";
            vm.Posts = new List<Post>();
            using (BlogDbContext db = new BlogDbContext()){
                vm.Posts = db.Posts.ToList();
            }
            return View(vm);
        }
        public ActionResult Create() { return View(); } // Show CRAETE page
        
        [HttpPost] // Process the CREATE page
        public ActionResult Create(CreatePostViewModel model) {
            Post temppost = new Post();
            temppost.Title = model.Title;
            temppost.Content = model.Body;
            temppost.BlogId = 1;
            using(BlogDbContext db = new BlogDbContext()){
                db.Posts.Add(temppost);
                db.SaveChanges();
            }
            return RedirectToAction("Index");
        }
        // Show UPDATE page 
        public ActionResult Update(int Id) {
            UpdatePostViewModel vm = new UpdatePostViewModel();
            vm.Msg = "Update the following post...";
            using (BlogDbContext db = new BlogDbContext()) {
                vm.Post =  db.Posts.Find(Id); 
            }
            return View(vm); 
        } 
        [HttpPost] // Process the UPDATE page
        public ActionResult Update(UpdatePostViewModel vm) {
            using (BlogDbContext db = new BlogDbContext()) {
                Post tpost = new Post();
                tpost = db.Posts.Find(vm.Post.PostId);
                tpost.Title = vm.Post.Title;
                tpost.Content = vm.Post.Content;
                db.SaveChanges();
            }
            return RedirectToAction("Index");
        }

        // Perform the Delete
        public ActionResult Delete(int Id) {
            using (BlogDbContext db = new BlogDbContext()) {
                Post tpost = new Post();
                tpost = db.Posts.Find(Id);
                db.Posts.Remove(tpost);
                db.SaveChanges();
            }
            return RedirectToAction("Index");
        }


    }
}